package com.jsy.common.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Trie {
    String word;
    Map<Character, Trie> children;
    boolean isWord;
    public Trie() {
        children = new HashMap<>();
        isWord = false;
    }
    public void insert(String word) {
        Trie cur = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.children.get(c) == null) {
                cur.children.put(c,new Trie());
            }
            cur = cur.children.get(c);
        }
        cur.isWord = true;
        cur.word = word;
    }
    public boolean search(String word) {
        Trie cur = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.children.get(c) == null) {
                return false;
            }
            cur = cur.children.get(c);
        }
        return cur.isWord;
    }

    public boolean startsWith(String prefix) {
        Trie cur = this;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (cur.children.get(c) == null) {
                return false;
            }
            cur = cur.children.get(c);
        }
        return true;
    }
}
